import shop from '../api/shop';
import * as types from '../constants/ActionTypes';


const receiveProducts = products => ({
  type: types.RECEIVE_PRODUCTS,
  products
});

// 函数返回了一个函数
// Thunk middleware 知道如何处理函数。
// 这里把 dispatch 方法通过参数的形式传给函数，
// 以此来让它自己也能 dispatch action。
export const getAllProducts = () => dispatch => {
  // products参数是回调回来的
  shop.getProducts(products => {
    dispatch(receiveProducts(products));
  });
};

const addToCartUnsafe = productId => ({
  type: types.ADD_TO_CART,
  productId
});

export const addToCart = productId => (dispatch, getState) => {
  if (getState().products.byId[productId].inventory > 0) {
    dispatch(addToCartUnsafe(productId))
  }
};

export const checkout = products => (dispatch, getState) => {
  const { cart } = getState();

  dispatch({
    type: types.CHECKOUT_REQUEST
  });
  shop.buyProducts(products, () => {
    dispatch({
      type: types.CHECKOUT_SUCCESS,
      cart
    });
    // Replace the line above with line below to rollback on failure:
    // dispatch({ type: types.CHECKOUT_FAILURE, cart })
  });
};
